
//
//  YYYHomeController.swift
//  Sina12
//
//  Created by yang on 2017/9/21.
//  Copyright © 2017年 成品家（北京）网络科技有限公司. All rights reserved.
//

import UIKit

//全局常量
//原创微博
private let cellID = "cellID"

class YYYHomeController: YYYBaseViewController {

    //下拉刷新标记
    var isPullUp = false
    
    //微博视图模型
    private lazy var statusViewModel = YYYHomeStatusViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        //注册监听者
        NotificationCenter.default.addObserver(self, selector: #selector(photoBrowser), name: NSNotification.Name(PhotoBrowserNotification), object: nil)
    }
    
    @objc private func photoBrowser(notification: NSNotification)
    {
        guard let userInfo = notification.userInfo,
              let selectedIndex = userInfo[PhotoBrowserSelectedIndexKey] as? Int,
              let urls = userInfo[PhotoBrowserUrlsKey] as? [String],
              let imageViews = userInfo[PhotoBrowserParentImageViewsKey] as? [UIImageView] else
        {
            return
        }
        
        //浏览控制器
        let browserVC = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViews)
        present(browserVC, animated: true, completion: nil)
    }
    //注销通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //加载首页数据
    override func loadData()
    {
        refreshControl.beginRefreshing()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
            self.statusViewModel.loadStatusListData(isPullUp: self.isPullUp) { (shouldRefresh) in
                //负责界面UI的处理
                self.isPullUp = false
                
                //结束刷新
                self.refreshControl.endRefreshing()
                
                if shouldRefresh
                {
                    print("刷新表格")
                    self.baseTableView.reloadData()
                }
            }
        }
    }
    
    @objc private func showFriends()
    {
        let friendVC = YYYFriendViewController()
        navigationController?.pushViewController(friendVC, animated: true)
    }
}

extension YYYHomeController
{
    //重写父类方法
    override func setupTableView() {
        super.setupTableView()

        //注册cell
        baseTableView.register(YYYHomePageCell.self, forCellReuseIdentifier: cellID)
   
        //取消分割线
        baseTableView.separatorStyle = .none
        //设置导航栏标题
        setupNavigationTitle()
    }
    //设置导航栏标题
    private func setupNavigationTitle()
    {
        //customNavigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
        
        let title = YYYNetworkManager.shared.userAccount.screen_name
        //重载构造函数
        let navButton = YYYNavigationButton.init(title: title)
        navButton.addTarget(self, action: #selector(navButtonAction), for: .touchUpInside)
        customNavigationItem.titleView = navButton
    }
    //点击导航栏事件
    @objc private func navButtonAction(navButton: YYYNavigationButton)
    {
        navButton.isSelected = !navButton.isSelected
    }
}

extension YYYHomeController
{
    //段数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    //行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModel.statusListArray.count
    }
    //创建cell
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let homeViewModel = statusViewModel.statusListArray[indexPath.row]
        //取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! YYYHomePageCell
        cell.selectionStyle = .none
        cell.viewModel = homeViewModel
        //设置cell代理，只是传递了一个指针地址
        cell.delegate = self
        //返回cell
        return cell
    }
    //设置行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let homeViewModel = statusViewModel.statusListArray[indexPath.row]
        return homeViewModel.rowHeight
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0
        {
            return
        }
        let count = tableView.numberOfRows(inSection: section) - 1
        if row == count && !isPullUp {
            print("上拉加载")
            isPullUp = true
            loadData()
        }
        
    }
}

extension YYYHomeController: YYYHomePageCellDelegate
{
    //实现cell的协议方法
    func homePageCellDidSelectedUrlString(urlString: String)
    {
        let webVC = YYYWebViewController()
        webVC.title = "网页"
        webVC.urlString = urlString
        navigationController?.pushViewController(webVC, animated: true)
    }
}
